import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import * as echarts from 'echarts';
import styles from './Home.module.css';

const getUser = () => {
    try {
        const u = localStorage.getItem('user');
        return u ? JSON.parse(u) : null;
    } catch {
        return null;
    }
};

const AdminHome: React.FC = () => {
    const navigate = useNavigate();
    const user = getUser();
    const username = user?.username || '用户';
    const role = user?.role || '访客';

    const [dashboardData, setDashboardData] = useState<{
        totalStudents: number;
        activeStudents: number;
        totalColleges: number;
        totalClasses: number;
        collegeDistribution: Array<{ name: string; count: number }>;
        marketingDistribution: Array<{ name: string; count: number }>;
        genderDistribution: Record<string, number>;
        enrollmentByMonth: number[];
    } | null>(null);

    const [loading, setLoading] = useState(true);

    // 从后端获取统计数据
    useEffect(() => {
        const base = 'http://localhost:3001';
        const safeFetch = async (url: string) => {
            try {
                const res = await fetch(url);
                console.log('API响应状态:', res.status, res.ok);
                if (!res.ok) {
                    console.error('API请求失败:', res.status, res.statusText);
                    return null;
                }
                const data = await res.json();
                console.log('API返回数据:', data);
                return data;
            } catch (error) {
                console.error('API请求异常:', error);
                return null;
            }
        };

        // 获取Dashboard统计数据
        console.log('开始请求Dashboard数据...');
        safeFetch(`${base}/api/dashboard/stats`).then(data => {
            if (data) {
                console.log('设置Dashboard数据:', data);
                setDashboardData(data);
            } else {
                console.log('未获取到Dashboard数据');
            }
            setLoading(false);
        });
    }, []);

    const kpis = useMemo(() => {
        if (!dashboardData) {
            return [
                { label: '总学生数', value: '0' },
                { label: '活跃学生', value: '0' },
                { label: '学院数量', value: '0' },
                { label: '班级数量', value: '0' },
            ];
        }
        return [
            { label: '总学生数', value: String(dashboardData.totalStudents) },
            { label: '活跃学生', value: String(dashboardData.activeStudents) },
            { label: '学院数量', value: String(dashboardData.totalColleges) },
            { label: '班级数量', value: String(dashboardData.totalClasses) },
        ];
    }, [dashboardData]);

    const shortcuts = [
        { id: 'stu', text: '学生管理', path: '/admin/students' },
        { id: 'cls', text: '班级管理', path: '/admin/students/classes' },
        { id: 'att', text: '考勤管理', path: '/admin/students/kaoqing' },
        { id: 'grd', text: '成绩管理', path: '/admin/grades' },
        { id: 'exp', text: '数据导出', path: '/admin/dashboard' },
        { id: 'set', text: '系统设置', path: '/admin/settings' },
    ];

    const todos = [
        { text: `查看待处理事项`, path: '/admin/students' },
        { text: `查看学生信息`, path: '/admin/students/dormitories' },
    ];

    const notices = [
        { text: '系统消息：周五 18:00 维护升级', path: '/admin/settings' },
        { text: '公告：新版导入模板已发布', path: '/admin/dashboard' },
    ];

    const logout = () => {
        if (window.confirm('确定要退出登录吗？')) {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            navigate('/login');
        }
    };

    // ECharts 容器
    const chartRef1 = useRef<HTMLDivElement | null>(null);
    const chartRef2 = useRef<HTMLDivElement | null>(null);
    const chartRef3 = useRef<HTMLDivElement | null>(null);
    const chartRef4 = useRef<HTMLDivElement | null>(null);

    // 渲染图表
    useEffect(() => {
        if (!dashboardData) return;

        // 检查所有必需的数据是否存在
        if (!dashboardData.genderDistribution ||
            !dashboardData.collegeDistribution ||
            !dashboardData.marketingDistribution ||
            !dashboardData.enrollmentByMonth) {
            console.log('等待数据加载...');
            return;
        }

        const inst1 = chartRef1.current ? echarts.init(chartRef1.current) : null;
        const inst2 = chartRef2.current ? echarts.init(chartRef2.current) : null;
        const inst3 = chartRef3.current ? echarts.init(chartRef3.current) : null;
        const inst4 = chartRef4.current ? echarts.init(chartRef4.current) : null;

        // 图表1: 学生入学时间趋势（使用后端数据）
        const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];

        inst1?.setOption({
            title: { text: '学生入学时间趋势', left: 'center', textStyle: { fontSize: 14 } },
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: months },
            yAxis: { type: 'value', name: '人数' },
            series: [{
                type: 'line',
                data: dashboardData.enrollmentByMonth || [],
                smooth: true,
                areaStyle: { opacity: 0.3 },
                itemStyle: { color: '#3b82f6' }
            }]
        });

        // 图表2: 性别分布（使用后端数据）
        const genderData = Object.entries(dashboardData.genderDistribution || {}).map(([name, value]) => ({
            name,
            value
        }));

        inst2?.setOption({
            title: { text: '学生性别分布', left: 'center', textStyle: { fontSize: 14 } },
            tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
            series: [{
                type: 'pie',
                radius: ['40%', '70%'],
                data: genderData,
                label: { show: true, formatter: '{b}: {c}' },
                color: ['#3b82f6', '#ef4444', '#10b981']
            }]
        });

        // 图表3: 学院分布（使用后端数据）
        const collegeData = (dashboardData.collegeDistribution || [])
            .sort((a, b) => b.count - a.count)
            .map(item => ({ name: item.name, value: item.count }));

        inst3?.setOption({
            title: { text: '学院学生分布', left: 'center', textStyle: { fontSize: 14 } },
            tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
            series: [{
                type: 'pie',
                radius: '60%',
                data: collegeData,
                label: { show: true, formatter: '{b}: {c}' },
                color: ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#06b6d4']
            }]
        });

        // 图表4: 市场部门分布（使用后端数据）
        const marketingData = [...(dashboardData.marketingDistribution || [])]
            .sort((a, b) => b.count - a.count);

        inst4?.setOption({
            title: { text: '市场部门学生分布', left: 'center', textStyle: { fontSize: 14 } },
            tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
            xAxis: { type: 'category', data: marketingData.map(item => item.name), axisLabel: { rotate: 45 } },
            yAxis: { type: 'value', name: '人数' },
            series: [{
                type: 'bar',
                data: marketingData.map(item => item.count),
                itemStyle: { color: '#8b5cf6' }
            }]
        });

        const onResize = () => {
            inst1?.resize(); inst2?.resize(); inst3?.resize(); inst4?.resize();
        };
        window.addEventListener('resize', onResize);
        return () => {
            window.removeEventListener('resize', onResize);
            inst1?.dispose(); inst2?.dispose(); inst3?.dispose(); inst4?.dispose();
        };
    }, [dashboardData]);

    return (
        <div className={styles.container}>
            {/* 一、系统概览与欢迎模块 */}
            <div className={styles.section}>
                <div className={styles.sectionBody}>
                    <div className={styles.welcome}>
                        <div className={styles.welcomeLeft}>
                            <h2>云枢学控</h2>
                            <div>欢迎，{username}（{role}）</div>
                            <div style={{ color: '#6b7280' }}>当前版本 v1.0.0 · <a href="#" onClick={e => { e.preventDefault(); navigate('/admin/dashboard'); }}>更新日志</a></div>
                        </div>
                        <div className={styles.actions}>
                            <button className={styles.btn} onClick={logout}>退出登录</button>
                        </div>
                    </div>
                </div>
            </div>

            {/* 二、核心数据卡片区 */}
            <div className={styles.section}>
                <div className={styles.sectionHeader}>核心数据</div>
                <div className={styles.sectionBody}>
                    <div className={styles.kpiGrid}>
                        {kpis.map(k => (
                            <div key={k.label} className={styles.kpiCard}>
                                <div className={styles.kpiLabel}>{k.label}</div>
                                <div className={styles.kpiValue}>{k.value}</div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* 三、快捷功能入口 */}
            <div className={styles.section}>
                <div className={styles.sectionHeader}>快捷功能</div>
                <div className={styles.sectionBody}>
                    <div className={styles.shortcutGrid}>
                        {shortcuts.map(s => (
                            <div key={s.id} className={styles.shortcutCard} onClick={() => navigate(s.path)}>
                                {s.text}
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* 四、待办事项与通知 */}
            <div className={styles.twoCol}>
                <div className={styles.section}>
                    <div className={styles.sectionHeader}>待办事项</div>
                    <div className={styles.sectionBody}>
                        <div className={styles.list}>
                            {todos.map((t, idx) => (
                                <div key={idx} className={styles.listItem} onClick={() => navigate(t.path)}>
                                    <span>{t.text}</span>
                                    <span style={{ color: '#3b82f6', cursor: 'pointer' }}>去处理</span>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
                <div className={styles.section}>
                    <div className={styles.sectionHeader}>通知公告</div>
                    <div className={styles.sectionBody}>
                        <div className={styles.list}>
                            {notices.map((n, idx) => (
                                <div key={idx} className={styles.listItem} onClick={() => navigate(n.path)}>
                                    <span>{n.text}</span>
                                    <span style={{ color: '#3b82f6', cursor: 'pointer' }}>查看</span>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>

            {/* 五、数据统计与趋势图表 */}
            <div className={styles.section}>
                <div className={styles.sectionHeader}>数据统计与趋势</div>
                <div className={styles.sectionBody}>
                    {loading ? (
                        <div style={{ textAlign: 'center', padding: '40px', color: '#6b7280' }}>
                            加载中...
                        </div>
                    ) : !dashboardData ? (
                        <div style={{ textAlign: 'center', padding: '40px', color: '#ef4444' }}>
                            无法加载数据，请检查后端服务是否正常运行
                        </div>
                    ) : (
                        <div className={styles.chartsGrid}>
                            <div ref={chartRef1} className={styles.chartBox} />
                            <div ref={chartRef2} className={styles.chartBox} />
                            <div ref={chartRef3} className={styles.chartBox} />
                            <div ref={chartRef4} className={styles.chartBox} />
                        </div>
                    )}
                </div>
            </div>

            {/* 六、操作指南与系统提示 */}
            <div className={styles.section}>
                <div className={styles.sectionHeader}>操作指南与系统提示</div>
                <div className={styles.sectionBody}>
                    <div className={styles.guideList}>
                        <div>· 新手引导：快速了解学生管理、班级管理等核心流程</div>
                        <div>· 使用注意：导入前请使用最新模板，确认字段匹配</div>
                        <div>· 更新说明：v1.0.0 新增考勤统计、优化成绩导入</div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default AdminHome;


